package mc.support.util;

import mc.support.support.pojo.Fragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: francis Yun    <br/>
 * Date: 2013-12-09  <br/>
 */
public final class SliceUtil {

    private SliceUtil() {}


    /**
     * similar to subList method
     * */
    public static <T> List<T> doSlice(List<T> total, int begin, int offset) {
        if ( null == total || begin < 0 || offset < 0) {
            return null;
        }
        int len = total.size();

        List<T> slice = new ArrayList<T>();
        for ( int i = begin; i <= (begin + offset) && i < len; i++ ) {
            slice.add( total.get( i ) );
        }

        return slice;
    }

    public static <T> Fragment<T> sliceToFragment(List<T> total, int begin, int offset) {
        if ( null == total || begin < 0 || offset < 0 ) {
            return null;
        }
        int totalSize = total.size();
        List<T> content = doSlice( total, begin, offset );
        return createFragment( content, begin, offset, totalSize );
    }

    public static <T> Fragment<T> createFragment(List<T> content, int begin,
                                                 int offset, int totalSize) {
        if ( begin < 0 || offset < 0 || totalSize < 0 || null == content ) {
            return null;
        }
        Fragment<T> fragment = new Fragment<T>();
        fragment.setContent( content );
        fragment.setTotalSize( totalSize );
        fragment.generateIndexes( begin, offset );

        return fragment;
    }

}
